package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.security.sasl.AuthorizeCallback;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    private static final String WE_CHAT_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Resource
    private UserMapper userMapper;
    @Resource
    private WeChatProperties weChatProperties;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //1.获取用户唯一id
        String openid = getOpenid(userLoginDTO);

        //2.拿到openid 到数据库查询这个id是否存在
        User user = userMapper.getByOpenId(openid);
        //2.1 不存在,新增数据到数据库,返回user对象
        if(Objects.isNull(user)){
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insertUser(user);
        }
        //2.2 已存在,直接返回

        return user;
    }

    /**
     * 获取用户ID
     * @param userLoginDTO
     * @return
     */
    private String getOpenid(UserLoginDTO userLoginDTO){
        //1.向服务器发起请求,获取openid
        //请求地址 请求方式 get 参数 响应值
        //https://api.weixin.qq.com/sns/jscode2session
        //拼接参数
        Map<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WE_CHAT_URL, map);
        //阿里的工具类
        //将json内的openid获取到
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = (String) jsonObject.get("openid");
        return openid;
    }
}
